import {formatTimeComponents} from '@/utils/public'

/**
 * Adjusts the minutes of a given date to the next multiple of 10.
 *
 * @param {Date} date - The date whose minutes needs to be adjusted.
 * @returns {Date} - The adjusted date.
 */
const adjustMinutes = date => {
    const adjustedMinute = Math.ceil(date.getMinutes() / 10) * 10
    date.setMinutes(adjustedMinute)
    return date
}

/**
 * Generates a URL for a cloud image based on a given date and type.
 *
 * @param {Date} date - The date for which the cloud image URL is to be generated.
 * @param {string} type - The type of cloud image (e.g. "local/infrared").
 * @returns {Object} - An object containing the formatted time and the cloud image URL.
 */
function generateUrlFromDate(date, type) {
    const { year, month, day, hour, minute } = formatTimeComponents(date)

    return {
        time: `${year}年${month}月${day}日 ${hour}时${minute}分`,
        url: `http://27.156.118.74:18800/images/cloud/${type}/${year}${month}/${day}/${year}${month}${day}${hour}${minute}.jpg`
    }
}

/**
 * Generates an array of cloud image URLs based on a provided time range and location.
 *
 * @param {Date | string} startTime - The start time for generating URLs. Defaults to 30 minutes before the current time.
 * @param {Date | string} endTime - The end time for generating URLs. Optional.
 * @param {number | string} location - The location for which cloud images should be generated.
 * @returns {Array} - An array of cloud image URLs within the specified time range and location.
 */
function generateCloudImageUrls(
    startTime = new Date(new Date().getTime() - 30 * 60 * 1000),
    endTime = null,
    location = '1'
) {
    if (!endTime) {
        endTime = startTime
        startTime = new Date(endTime.getTime() - 10 * 60 * 1000)
    }

    const path = location === '1' ? 'local/infrared' : 'tw/hs1p'
    startTime = adjustMinutes(startTime)
    const minutesDifference = (endTime.getTime() - startTime.getTime()) / (60 * 1000)
    const intervals = Math.floor(minutesDifference / 10)

    return Array(intervals + 1)
        .fill(null)
        .map((_, idx) => {
            const currentDateTime = new Date(startTime.getTime() + idx * 10 * 60 * 1000)
            return generateUrlFromDate(currentDateTime, path)
        })
}

export {generateCloudImageUrls};
